package com.xiaofan.controller;

import com.xiaofan.bean.User;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * @author 晓帆
 * @version 1.0
 **/
@RestController
@RequestMapping("user")
public class UserController {
    @RequestMapping("login")
    public void loginIn(@Validated User user, BindingResult bindingResult){//使用@Valid或者@Validated开启校验,BindingResult可以让校验结果进入handel方法，自己处理校验失败，防止给用户400页面

        //判断参数是否全部合法，存在不合法就为true
        if (bindingResult.hasErrors()){
            FieldError fieldError = bindingResult.getFieldError();
            //获得错误参数名，也就是成员变量名
            String field = fieldError.getField();
            //获得不合法的请求参数的值
            Object rejectedValue = fieldError.getRejectedValue();
            //获得失败的消息,javabean注解上的message
            String defaultMessage = fieldError.getDefaultMessage();
            System.out.println(field+"不合法："+defaultMessage);

        }
        System.out.println(user);

    }
}
